﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LiveSSOForDotNet.Business;
namespace LiveSSOForDotNet
{
    public partial class RegisterWindowsLiveID : System.Web.UI.Page
    {
        const string LoginCookie = "webauthtoken";

        // Initialize the WindowsLiveLogin module.
        static WindowsLiveLogin wll = new WindowsLiveLogin(true);

        static DateTime ExpireCookie = DateTime.Now.AddYears(-10);
        static DateTime PersistCookie = DateTime.Now.AddYears(10);
        protected static string AppId = wll.AppId;

        private Users User_sql = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            User_sql = new Users();
             
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            HttpRequest req = HttpContext.Current.Request;
            HttpResponse res = HttpContext.Current.Response;
            HttpCookie loginCookie = req.Cookies[LoginCookie];
            if (loginCookie != null)
            {
                string token = loginCookie.Value;

                if (!string.IsNullOrEmpty(token))
                {
                    WindowsLiveLogin.User user = wll.ProcessToken(token);
                    string windowsLiveID = "";
                    if (user != null)
                    {
                        windowsLiveID = user.Id;
                        string userID = txtUserID.Text;
                        string email = txtEmail.Text;
                        bool insertSuccess = User_sql.InsertUsers(userID, email, windowsLiveID);
                        loginCookie.Value = user.Token;
                        loginCookie.Expires = PersistCookie;
                        res.Cookies.Add(loginCookie);
                        res.Redirect("Default.aspx");
                        //if (insertSuccess)
                        //{

                        //    loginCookie.Value = user.Token;
                        //    loginCookie.Expires = PersistCookie;
                        //    res.Cookies.Add(loginCookie);
                        //    res.Redirect("Default.aspx");
                        //    //res.End();
                        //}
                    }
                }
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            txtUserID.Text = string.Empty;
            txtEmail.Text = string.Empty;
        }
    }
}
